#!/usr/bin/env python

import ConfigParser
import os

class ConfClient:
	"""Class for reading configuration from ini file"""

#	somewhy python can`t correctly interpritate path like this "~/.btx/config.ini", so we need to get home dir from environment variable	
	def __init__(self,conf_file="%s/.btx/config.ini" % os.environ["HOME"]):
		"""Class constructor
		
		Parameters:
		conf_file: path to config file. Default: ~/.btx/config.ini
		"""
		self.config = conf_file			

		self.client = ConfigParser.ConfigParser()
		
		if os.path.exists(self.config):
#			file exists
			self.client.read(self.config)
#			set self.state to true if file has section [connect] abd to false if it doesn`t(probably, empty file)
			self.state = self.client.has_section("connect")
		else:
#			does not exist
			try:
#				try to create configuration directory
				os.mkdir(os.path.dirname(self.config))
			except:
				pass
			self.client.read(self.config)
			self.state = False

	def load_conf(self):
		"""Loads configuration from file"""
		user = self.client.get("connect","user")
		passw = self.client.get ("connect","passw")
		domain = self.client.get ("connect","domain")
		sendto = self.client.get ("connect","sendto")
		
		return user,passw,domain,sendto

	def save_conf(self,user,passw,domain,sendto):
		"""Saves configuration in file"""
		if not self.client.has_section("connect"):
#			file does not have section [connect], probably it`s empty
			self.client.add_section("connect")	
		
		self.client.set ("connect","user",user.strip("\""))
		self.client.set ("connect","passw",passw.strip("\""))
		self.client.set ("connect","domain",domain.strip("\""))
		self.client.set ("connect","sendto",sendto.strip("\""))

#		save file to the same location
		self.client.write(open(self.config,"w"))
